<template>
  <div class="table_con">
    <tableComponents :isShow="false" @toAdd="dialogFormVisible = true" :isHaveExport="false" :isHavePagination="false">
      <template v-slot:table>
        <el-table :data="listData" row-key="id" border :tree-props="{ children: 'z' }" style="width: 99.9%">
          <el-table-column label="分类名称" min-width="200">
            <template slot-scope="scope">
              <div class="tree_yiji">
                {{ scope.row.title }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="排序" sortable :sort-method="sorta" align="center" min-width="95">
            <template slot-scope="scope">
              <div>
                <el-input @change="sortNew(scope.$index, scope.row)" v-enterNumber v-model="scope.row.sort" autocomplete="off" size="small">
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品图片" min-width="100" align="center">
            <template slot-scope="scope">
              <div class="img_bor">
                <img :src="$fnc.getImgUrl(scope.row.piclink)" alt />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="英文标识" min-width="150" align="center">
            <template slot-scope="scope">
              <div class="tree_yiji">
                {{ scope.row.iden }}
              </div>
            </template>
          </el-table-column>

          <el-table-column label="是否显示" min-width="150" align="center">
            <template slot-scope="scope">
              <el-switch class="zdySwith" :width="82" v-model="scope.row.show" active-color="#1aad19" inactive-color="#ffffff" active-text="已开启"
                  inactive-text="已关闭" active-value="1" @change="gethandSwitch($event, scope.row)" inactive-value="0"></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" min-width="200" align="center">
            <template slot-scope="scope">{{
              scope.row.created_time | getTimeFormat
            }}</template>
          </el-table-column>

          <el-table-column label="操作" min-width="200" align="center">
            <template slot-scope="scope">
              <el-button :loading="$store.state.isLoading" type="primary" size="mini" @click="openDetails(scope.row.id)">字段管理</el-button>
              <el-button :loading="$store.state.isLoading" type="primary" size="mini" @click="updateMenuLi(scope.row)">编辑</el-button>
              <el-button :loading="$store.state.isLoading" size="mini" @click="deleteMenu(scope.row.id)" type="danger">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </tableComponents>

    <el-dialog title="编辑分类" :close-on-click-modal="false" width="800px" @close="closeDio" :visible.sync="dialogFormVisible" class="tl size_13">
      <el-form :model="ruleForm" center :rules="rules" ref="ruleForm" :label-width="formLabelWidth">
        <el-form-item label="分类名称" prop="title">
          <el-col :span="12">
            <el-input v-model="ruleForm.title" autocomplete="off" placeholder="请输入分类名称" size="small"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="英文标识" prop="iden" v-if="op && op.length <= 1">
          <el-col :span="12">
            <el-input v-model="ruleForm.iden" autocomplete="off" placeholder="请输入英文标识" size="small"></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="上级分类" v-if="!ruleForm.id">
          <el-col :span="12">
            <el-cascader :options="listData" :props="optionProps" :show-all-levels="false" v-model="op" size="small" change-on-select
                style="width: 100%" :placeholder="placeText" clearable @change="changeMenu"></el-cascader>
          </el-col>
        </el-form-item>

        <el-form-item label="图片地址" prop="piclink">
          <el-col :span="12" class="tl">
            <el-input v-model="ruleForm.piclink" clearable disabled class="mar_bottom_5" size="small"></el-input>
            <uploadpic :piclink="ruleForm.piclink" :width="150" :height="150" :real_width="50" :real_height="50" :is_more="false"
                @send_pic="onSuccess">
            </uploadpic>
          </el-col>
        </el-form-item>

        <el-form-item>
          <el-button :loading="$store.state.isLoading" type="primary" @click="addMenu('ruleForm')" size="mini">
            立即提交
          </el-button>
          <el-button :loading="$store.state.isLoading" @click="dialogFormVisible = false" size="mini">
            取 消
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import tableTree from "../../../components/currency/tableThree";
import menuForm from "@/components/currency/menuMessageBox.vue";
import HeadTitle from "@/components/currency/HeadTitle.vue";

import uploadpic from "@/components/page/pic/up_pic";
export default {
  data () {
    var checkIden = (rule, value, callback) => {
      setTimeout(() => {
        if (!/^[a-zA-Z]([_a-zA-Z0-9]{0,})$/.test(value)) {
          callback(new Error("请输入以英文为开头的标识，可拼接下划线和数字"));
        } else {
          callback();
        }
      }, 500);
    };
    return {
      tabledialogVisible: false,
      listData: [],
      show: false,
      xy_down: 0,
      xy_down_text: "全部隐藏",
      objj: "",
      hackReset: true,
      add: "",
      dialogFormVisible: false,
      ruleForm: {
        title: "",
        parent_id: "0",
        show: "",
        sort: "",
      },
      rules: {
        title: [{ required: true, message: "请输入分类标题", trigger: "blur" }],
        iden: [{ validator: checkIden, trigger: "blur" }],
      },
      piclinks: "",
      formLabelWidth: "120px",
      op: [],
      placeText: "添加上级分类,不选择默认为一级",
      optionProps: {
        value: "id",
        label: "title",
        children: "z",
      },
      ex: [],
    };
  },

  computed: {},
  watch: {},
  created () {
    this.get_class_info();
  },
  methods: {
    gotolink (id) {
      let routeData = this.$router.resolve({
        path: "/index/classify/info",
        query: { id: id },
      });
      window.open(routeData.href, "_blank");
    },
    onSuccess (pic) {
      this.ruleForm.piclink = pic;
    },
    toObj (obj, str) {
      obj = obj || {};
      obj = JSON.parse(JSON.stringify(obj));
      obj.commandStr = str;
      return JSON.parse(JSON.stringify(obj));
    },
    openDetails (id) {
      console.log(id);
      let routeData = this.$router.resolve({
        path: "/index/classify/classfield",
        query: { id: id },
      });
      window.open(routeData.href, "_blank");
    },
    get_class_info () {
      this.$api.getClassify.getClassInfo().then((res) => {
        if (res.data.code == 200) {
          this.listData = res.data.result;
        }
      });
    },
    sorta (a, b) {
      return b - a;
    },
    sortNew (index, row) {
      var params = {};
      params.title = row.title;
      params.parent_id = row.parent_id;
      params.sort = row.sort;
      params.id = row.id;
      params.show = row.show;
      this.$api.getClassify.editClassInfo(params).then((res) => {
        if (res.data.code !== 200) {
          this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
        }
      });
    },
    getEx (arr) {
      this.ex = arr;
    },
    closeDio () {
      this.dialogFormVisible = false;
      this.ruleForm = {
        title: "",
        parent_id: "0",
        url: "",
        piclink: "",
      };
      this.op = [];
    },
    deleteMenu (id) {
      this.$swal({
        title: "您确定要删除这条信息吗",
        text: "删除后将无法恢复，请谨慎操作！",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "是的，我要删除",
        cancelButtonText: "容我三思",
      }).then((willDelete) => {
        if (willDelete.value) {
          var params = { id };
          this.$api.getClassify.deleteClassInfo(params).then((res) => {
            if (res.status == 200 && res.data.code == 400) {
              this.$fnc.alertError(res.data.code_desc, res.data.result);
            } else if (res.data.code == 200) {
              this.$swal("删除成功！", "您已经删除了这条信息。", "success");
              this.get_class_info();
            } else {
              this.$swal("删除失败！", res.data.result, "error");
            }
          });
        }
      });
    },
    updateMenuLi (row) {
      this.dialogFormVisible = true;
      this.ruleForm = JSON.parse(JSON.stringify(row));
      this.op = row.parent_id;
    },
    toggle () {
      this.xy_down += 1;
      if (this.xy_down % 2 == 0) {
        this.xy_down_text = "全部隐藏";
      } else {
        this.xy_down_text = "全部显示";
      }
    },
    gethandSwitch (e, row) {
      var params = {};
      params.title = row.title;
      params.parent_id = row.parent_id;
      params.sort = row.sort;
      params.id = row.id;
      params.show = e;
      this.$api.getClassify.editClassInfo(params).then((res) => {
        if (res.data.code !== 200) {
          this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
        }
      });
    },

    addMenu (ruleForm) {
      this.$refs[ruleForm].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          var params = {};
          this.ruleForm.parent_id = this.ruleForm.parent_id || 0;
          params = this.ruleForm;
          if (params.z) {
            delete params.z;
          }
          if (params.id) {
            this.$api.getClassify.editClassInfo(params).then((res) => {
              if (
                res.data.code == 200 &&
                res.data.status == 1 &&
                res.data.result
              ) {
                this.$fnc.alertSuccess({ text: "修改成功" }); //成功弹出框
                this.get_class_info();
              } else {
                this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
                this.op = [];
              }
            });
          } else {
            this.$api.getClassify.addClassInfo(params).then((res) => {
              if (
                res.data.code == 200 &&
                res.data.status == 1 &&
                res.data.result
              ) {
                this.get_class_info();
                this.$fnc.alertSuccess({ text: "添加成功" }); //成功弹出框
              } else {
                this.$fnc.alertError(res.data.code_desc, res.data.result); //失败弹出框
              }
            });
          }
        } else {
          this.$message.error("请补充完整信息！");
          return false;
        }
      });
    },
    changeMenu (val) {
      this.ruleForm.parent_id = val[val.length - 1];
    },
  },
  components: {
    tableTree,
    menuForm,
    HeadTitle,
    uploadpic,
  },
};
</script>
